<?php
/**
 * Description of myActiveForm_dung
 * 
 * @author ds2t
 * @since 02-08-2013 - 16:49:14
 */
?>
<div class="grid <?php echo isset($this->htmlOptions['class']) ? $this->htmlOptions['class'] : '' ?>">
    <div class="grid-title">
        <div class="pull-left"><?php echo $this->title ?></div>

        <div class="clear"></div>
    </div>
    <div class="grid-content">
        <?php echo $form->errorSummary($this->model); ?>
        <?php
        $editor_ids = array(); // Danh sách ID của các Input hiển thị kiểu editor 
        $NoPhotoUrl = Yii::app()->controller->asset . "/images/no_photo.jpg";
        ?>
        <?php foreach ($this->columns as $info): ?>
            <?php
            $label = "";
            $input = "";
            $preview = "";
            $link = "";
            $error = "";
            $help = "";
            $value = "";
            if (is_array($info))
            {
                $attribute = $info['field'];
                $label = $form->labelEx($this->model, $attribute);
                $value = $this->model->{$attribute};
                /**
                 * ID của phần Input, phục vụ cho việc áp dụng các sự kiện js cho nó
                 */
                $inputID = CHtml::activeId($this->model, $attribute);

                /**
                 *  Nếu có truyền vào loại Input thì dùng loại đó nếu không thì 
                 *  dùng textField
                 */
                $type = (isset($info['type'])) ? $info['type'] : '';
                switch ($type)
                {
                    case "editor":
                        $editor_ids[] = $inputID;
                        $fieldType = 'textArea';
                        break;

                    case "image":
                        /**
                         * Upload ảnh
                         */
                        $fieldType = 'hiddenField';
                        /**
                         * Hiển thị ảnh được chọn
                         */
                        $imgSrc = $value != '' ? $value : $NoPhotoUrl;
                        $imgOption = array(
                            'id' => "prv_$inputID",
                            'style' => 'max-height:150px;',
                            'data-glisse-big' => $imgSrc,
                            'class' => 'tl',
                            'rel' => 'post',
                        );
                        $preview = CHtml::image($imgSrc, $help, $imgOption);
                        /**
                         * Các liên kết thao tác với ảnh
                         */
                        $browseOptions = array('onclick' => "return upload_file('$inputID')");
                        $linkBrowse = CHtml::link(Yii::t('form', 'Browse Files'), "#", $browseOptions);

                        $deleteOptions = array('onclick' => "return clear_image('$inputID')");
                        $linkDelete = CHtml::link(Yii::t('form', 'Clear image'), "#", $deleteOptions);

                        $link = "<div>$linkBrowse | $linkDelete</div>";
                        break;

                    case "upload":
                        /**
                         * Upload ảnh
                         */
                        $fieldType = 'textField';
                        /**
                         * Các liên kết thao tác với ảnh
                         */
                        $browseOptions = array('onclick' => "return upload_file('$inputID')");
                        $linkBrowse = CHtml::link(Yii::t('form', 'Browse Files'), "#", $browseOptions);

                        $deleteOptions = array('onclick' => "return clear_image('$inputID')");
                        $linkDelete = CHtml::link(Yii::t('form', 'Clear image'), "#", $deleteOptions);

                        $link = "<div>$linkBrowse | $linkDelete</div>";
                        break;

                    case "img_upload":
                        /**
                         * Upload nhieu ảnh
                         */
                        $fieldType = 'hiddenField';
                        /**
                         * Các liên kết thao tác với ảnh
                         */
                        $browseOptions = array('onclick' => "return upload_file('$inputID')");
                        $linkBrowse = CHtml::link(Yii::t('form', 'Browse Files'), "#", $browseOptions);
                        $linkUpload = '';
                        $deleteOptions = array('onclick' => "return clear_image('$inputID')");
                        $linkDelete = CHtml::link(Yii::t('form', 'Clear image'), "#", $deleteOptions);

                        $link = "<div>$linkBrowse | $linkDelete | $linkUpload</div>";
                        break;

                    case "hidden":
                        $fieldType = 'hiddenField';
                        $label = '';
                        break;

                    case "":
                        $fieldType = 'textField';
                        break;

                    default:
                        $fieldType = $type;
                        break;
                }


                /**
                 * Hiển thị dòng giải thích cho các Input     
                 */
                $help = (isset($info['help'])) ? $info['help'] : "";

                /**
                 * Nếu có truyền vào các Option cho thẻ input thì dùng                 
                 */
                $htmlOptions = (isset($info['htmlOptions'])) ? $info['htmlOptions'] : array();

                /**
                 *  Nếu có truyền vào data thì thuộc dạng lựa chọn, 
                 *  còn không thì thuộng dạng gõ
                 */
                $input = isset($info['data']) ?
                        $form->{$fieldType}($this->model, $attribute, $info['data'], $htmlOptions) :
                        $form->{$fieldType}($this->model, $attribute, $htmlOptions);
            }
            else
            {
                /**
                 * Trường hợp truyền vào là tên 1 cột trong csdl
                 */
                $label = $form->labelEx($this->model, $info);
                $input = $form->textField($this->model, $info);
                $error = $form->error($this->model, $info);
            };
            ?>            
            <div class="formRow">
                <?php echo $label; ?>
                <div class="formRight">
                    <?php echo $input; ?>
                    <?php echo $preview; ?>
                    <?php echo $link; ?>
                    <?php echo $error ?>
                    <?php if ($help != ""): ?>
                        <p class="help-block"><?php echo $help ?></p>
                    <?php endif; ?>
                    <div class="clear"></div>
                </div>
            </div>
        <?php endforeach; ?>      
        <div class="clear"></div>        
    </div>    
</div>
<!--Input fields END-->

<script src="<?php echo Yii::app()->controller->asset ?>/js/tiny_mce/tiny_mce.js"></script>
<script src="<?php echo Yii::app()->controller->asset ?>/js/bootstrap-colorpicker.js"></script>
<script src="<?php echo Yii::app()->controller->asset ?>/js/chosen.jquery.min.js"></script>
<script src="<?php echo Yii::app()->controller->asset ?>/js/autoresize.jquery.min.js"></script>
<script src="<?php echo Yii::app()->controller->asset ?>/js/jquery.tagsinput.min.js"></script>
<script src="<?php echo Yii::app()->controller->asset ?>/js/jquery.autotab.js"></script>
<script src="<?php echo Yii::app()->controller->asset ?>/js/app.form.js"></script>

<script>
    /*  TinyMCE - Javascript WYSIWYG Editor */
    tinyMCE.init({
        // General options
        mode: "exact", // selected textareas
        elements: "<?php echo implode(",", $editor_ids) ?>", // id of selected textarea
        theme: "advanced",
        width: "98%",
        height: "500",
        language: 'vi',
        plugins: "pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",
        // Theme options
        theme_advanced_buttons1: "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect",
        theme_advanced_buttons2: "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
        theme_advanced_buttons3: "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
        //    theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak",
        theme_advanced_toolbar_location: "top",
        theme_advanced_toolbar_align: "left",
        theme_advanced_statusbar_location: "bottom",
        theme_advanced_resizing: true,
        force_br_newlines: true,
        convert_urls: false,
        file_browser_callback: 'fileBrowserTinymce',
        // Drop lists for link/image/media/template dialogs
        template_external_list_url: "js/template_list.js",
        external_link_list_url: "js/link_list.js",
        external_image_list_url: "js/image_list.js",
        media_external_list_url: "js/media_list.js",
        // Replace values for the template plugin
        template_replace_values: {
            username: "Some User",
            staffid: "991234"
        }

    });

    function fileBrowserTinymce(field_name, url, type, win) {
<?php $params = array('lang' => Yii::app()->language, 'type' => 'tinymce'); ?>
        src = "<?php echo Yii::app()->controller->createUrl('files/index', $params) ?>";
        tinyMCE.activeEditor.windowManager.open({
            file: src,
            title: '<?php echo Yii::t('form', 'File manager') ?>',
            width: 900,
            height: 500,
            resizable: 'yes',
            inline: 'yes', // This parameter only has an effect if you use the inlinepopups plugin!
            popup_css: false, // Disable TinyMCE's default popup CSS
            close_previous: 'no'
        }, {
            window: win,
            input: field_name
        });
        return false;
    }

    function convertToSlug(Text)
    {
        // Xử lý ký tự Unicode
        in_chrs = 'áàảãạăắặằẳẵâấầẩẫậđéèẻẽẹêếềểễệóòỏõọôốồổỗộơớờởỡợúùủũụưứừửữựýỳỷỹỵÁÀẢÃẠĂẮẶẰẲẴÂẤẦẨẪẬĐÉÈẺẼẸÊẾỀỂỄỆÍÌỈĨỊíìỉĩịÓÒỎÕỌÔỐỒỔỖỘƠỚỜỞỠỢÚÙỦŨỤƯỨỪỬỮỰÝỲỶỸỴ',
                out_chrs = 'aaaaaaaaaaaaaaaaadeeeeeeeeeeeooooooooooooooooouuuuuuuuuuuyyyyyAAAAAAAAAAAAAAAAADEEEEEEEEEEEIIIIIiiiiiOOOOOOOOOOOOOOOOOOUUUUUUUUUUUUYYYYY'
        transl = {};

        eval('var chars_rgx = /[' + in_chrs + ']/g');
        for (var i = 0; i < in_chrs.length; i++)
        {
            transl[in_chrs.charAt(i)] = out_chrs.charAt(i);
        }
        Text = Text.replace(chars_rgx, function(match) {
            return transl[match];
        });

        Text = Text
                .toLowerCase()
                .replace(/ /g, '-')
                .replace(/[^\w-]+/g, '')
                .replace(/--/g, '-');

        // Bỏ đi các ký tự đặc biệt
        return Text;
    }
</script>



<div id="fileModal" class="modal hide fade" style="width: 800px;margin-bottom: 0;padding-bottom: 0"
     role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
        <h3 id="myModalLabel"><?php echo Yii::t('form', 'File manager') ?></h3>
    </div>
    <div class="modal-body" style="max-height: 700px;padding: 0;margin: 0"></div>
</div>
<script>
    function upload_file(field)
    {
        $("#fileModal").modal();
        $('#fileModal').on('shown', function() {
<?php $params2 = array('lang' => Yii::app()->language, 'dialog' => 'fileModal'); ?>
            src = "<?php echo Yii::app()->controller->createUrl('files/index', $params2) ?>";
            src += "&field=" + field;
            iframe = '<iframe width="100%" height="420px" src="' + src + '"  style="padding: 0;margin: 0;border: 0;overflow: auto" />';
            $(this).children('.modal-body').html(iframe);
        });

        return false;
    }

    function clear_image(field)
    {
        NoPhotoUrl = "<?php echo $NoPhotoUrl ?>";
        $("#prv_" + field).attr('src', NoPhotoUrl);
        $("#prv_" + field).attr('data-glisse-big', NoPhotoUrl);
        $("#" + field).attr('value', '');
        return false;
    }
</script>
